<template>
  <!-- 全部订单 -->
  <template v-if="active == 0">
    <el-button type="primary" @click="commonBaseBatchFn('order_re_inspection')" v-hasPermi="[userAuthList[type].recheck]">重检订单</el-button>
    <el-button type="primary" @click="commonBaseBatchFn('order_set_confirmed')" v-hasPermi="[userAuthList[type].confirm]">确认通过</el-button>
    <el-dropdown :max-height="290" class="my-dropdown" popper-class="my-dropdown" trigger="click" placement="bottom-start">
      <el-button type="primary">
        订单操作
        <svg-icon icon-class="arrow_down" class="text-[20px]"></svg-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu v-matomo>
          <el-dropdown-item command="a" @click="handleAdd" v-if="isPermission([userAuthList[type].add])">新增订单</el-dropdown-item>
          <el-dropdown-item @click="handleCancel" v-if="isPermission([userAuthList[type].batchCancel])"> 批量取消系统订单 </el-dropdown-item>
          <el-dropdown-item @click="batchQuoteRate" v-if="isPermission([userAuthList[type].batchCalculate])">批量重新计算订单利润</el-dropdown-item>
          <el-dropdown-item @click="handleSplitOrder" v-if="isPermission([userAuthList[type].split])"> 拆分订单 </el-dropdown-item>
          <el-dropdown-item @click="handleCombinedOrder" v-if="isPermission([userAuthList[type].merge])"> 合并订单 </el-dropdown-item>
          <el-dropdown-item @click="handleLibraryIntercept" v-if="isPermission([userAuthList[type].intercept])"> 库内拦截（未发货） </el-dropdown-item>

          <el-dropdown-item @click="handleBlacklist" v-if="isPermission([userAuthList[type].blacklist])"> 添加至黑名单 </el-dropdown-item>
          <el-dropdown-item @click="handleInvoice" v-if="isPermission([userAuthList[type].invoice])">导出发票</el-dropdown-item>

          <el-dropdown-item @click="handleInit" v-if="isPermission([userAuthList[type].batchInit])"> 批量初始化订单 </el-dropdown-item>
          <el-dropdown-item @click="handleChangeSku" v-if="isPermission([userAuthList[type].batchReplace])"> 批量替换订单SKU </el-dropdown-item>
          <el-dropdown-item @click="handleCancelEbay" v-if="isPermission([userAuthList[type].batchCancelEbay])">批量取消ebay订单</el-dropdown-item>
          <el-dropdown-item @click="handleOperation" v-if="isPermission([userAuthList[type].batchOperation])">批量修改订单优先级别</el-dropdown-item>
          <el-dropdown-item @click="handleRecipientUpdate" v-if="isPermission([userAuthList[type].recipientUpdate])">批量修改订单地址</el-dropdown-item>
          <el-dropdown-item @click="handleOrderExtract" v-if="isPermission([userAuthList[type].batchExtract])">批量提取订单信息</el-dropdown-item>

          <el-dropdown-item @click="handleBatchRemark" v-if="isPermission([userAuthList[type].shippedReturnRemark])">批量标记物流退回</el-dropdown-item>

          <el-dropdown-item @click="handleApplyRefund" v-if="isPermission([userAuthList[type].batchApplyRefund])">批量申请全额退款</el-dropdown-item>

          <el-dropdown-item @click="handleAddAccessory" v-if="isPermission([userAuthList[type].addAccessory])">订单附件管理</el-dropdown-item>

          <!-- // { label: "批量申请全额退款", fn: "onApplyRefund", isPer: "batchApplyRefund" }, -->
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-dropdown popper-class="my-dropdown" max-height="290" trigger="click" placement="bottom-start">
      <el-button type="primary">
        功能操作
        <svg-icon icon-class="arrow_down" class="text-[20px]"></svg-icon>
      </el-button>
      <template #dropdown>
        <template v-for="item in FUNCTION_OPERATE" :key="item.title">
          <div class="dropdownTitle">
            {{ item.title }}
          </div>
          <template v-for="n in item.options">
            <el-dropdown-item class="dropdown-item" :key="n.label" @click="handleBatchOperate(n)" v-if="isPermission([userAuthList[type][n.isPer]])">
              {{ n.label }}
            </el-dropdown-item>
          </template>
        </template>
      </template>
    </el-dropdown>

    <el-button plain class="ml-3" @click="queryShipmentStatus" v-hasPermi="[userAuthList[type].publishFail]"> 标发失败订单 </el-button>

    <el-button class="ml-3" @click="openShopSaleList" v-hasPermi="[userAuthList[type].shopSaleList]"> 订单销售数据 </el-button>

    <el-checkbox :value="props.showOrderProfit" label="显示订单利润" @change="showOrderProfitChange" />

    <div class="ml-auto flex items-center total text-color">
      <p v-if="totalInfo.total">
        订单总数：<span>{{ totalInfo.total }} </span>
      </p>
      <p class="ml-[4px]" v-if="totalInfo.order_amount">
        订单销售总额(不含税)：<span
          >USD {{ totalInfo.order_amount_us || 0 }}/CNY
          {{ totalInfo.order_amount || 0 }}
        </span>
      </p>
    </div>
    <el-button @click="handleExpand">
      <svg-icon icon-class="packUp" color="#3e66ee" style="color: #3e66ee" class="white transition-all" :class="{ 'rotate-[180deg] ': expandStatus }"></svg-icon>
      {{ expandStatus ? "全部收起" : "全部展开" }}
    </el-button>
    <!-- <el-button @click="expt" icon="Upload" style="margin-right: -8px" v-hasPermi="[userAuthList[type].export]">导出</el-button> -->
    <el-button @click="expt" style="margin-right: -8px" v-hasPermi="[userAuthList[type].export]">
      导出
      <template #icon> <svg-icon icon-class="upload-icon" class="text-[20px]"></svg-icon></template>
    </el-button>
  </template>
  <!-- 可合并订单 -->
  <template v-if="active == 1">
    <el-button type="primary" @click="onMerge"> 批量合并 </el-button>
    <el-button type="primary" @click="onNoMerge"> 不合并订单 </el-button>
  </template>
  <!-- 已合并订单 -->
  <template v-if="active == 2">
    <el-button type="primary" @click="onCancelMerge"> 批量取消合并 </el-button>
  </template>

  <div class="template">
    <!-- 批量替换订单SKU -->
    <ReplaceSku v-model="batchVisible.replaceSku" :rows="rows" @refresh="handleRefresh" />
    <!-- 拆分订单 -->
    <SplitOrder v-model="batchVisible.splitOrder" :data="rows" @refresh="handleRefresh" />
    <!-- 合并订单 -->
    <CombinedOrder v-model="batchVisible.combinedOrder" :rows="rows" @refresh="handleRefresh" />

    <ConfirmInput v-model="batchVisible.confirmInput" v-bind="getCurrentConfirm" @submit="handleConfirmSubmit" />
    <!-- 弹窗 表单编辑 -->
    <OrderConfirmInput v-model="batchVisible.orderConfirmInput" v-bind="orderCurrentConfirm" @submit="handleConfirmInputSubmit">
      <!-- 批量申请全额退款 -->
      <!-- <template #reason>
        <ReasonCascade ref="reasonCascade" :info="info" :platform_id="info.platform_id" :firstOption="firstOption" />
      </template> -->
      <!-- <template #refund_amount>
        <RefundAmountInput :value="info" />
      </template> -->
      <!-- 订单附件管理 -->
      <template #addAccessory="{ form }">
        <VText title="系统订单号" :value="form.order_sn" />
        <Accessory :data="form.attachment" type="list" />
      </template>
    </OrderConfirmInput>

    <!-- 批量修改发货仓库和运输方式 -->
    <ShippingMethod v-model="batchVisible.editShipping" :rows="rows" @submit="handleConfirmSubmit" />
    <!-- 批量手动标发订单 -->
    <MarkShipment v-model="batchVisible.markShipment" @submit="handleConfirmSubmit" :rows="rows" />
    <!-- 订单优先级 -->
    <OrderPriority v-model="batchVisible.orderPriority" :rows="rows" @submit="handleConfirmSubmit" />
    <!-- 批量手动导入追踪号 -->
    <VImport :download-url="downloadUrl" :call-back="importCallBack" :params-formatter="importParamsFormatter" v-model="batchVisible.import" ref="VImportRef" />
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef" v-if="dialogShow.DerivedCenter">
      <template #importBtn>
        <el-button type="primary" @click="outerExport('order_sku_flatten', '按订单维度导出')">按订单维度导出</el-button>
        <el-button type="primary" @click="outerExport('order_sku', '按SKU维度导出')">按SKU维度导出</el-button>
        <span>
          <el-button type="primary" @click="outerExport('order_distribution_sku_export', '按配货SKU导出')">配货SKU导出</el-button>
          <el-tooltip effect="dark" content="配货SKU导出是固定字段模板，不支持自定义选择字段" placement="top-end">
            <div class="dk-iconfont icon-Warning ml-[4px]"></div>
          </el-tooltip>
        </span>
      </template>
    </DerivedCenter>

    <!-- 店铺销售数据 -->
    <ShopSale ref="shopSaleRef" v-if="shopSaleShow" />

    <OutNumber ref="OutNumberRef"></OutNumber>

    <ImportNoNumber ref="ImportNoNumberRef" />

    <OrderExtractDtl ref="OrderExtractDtlRef" />
    <!-- 亚马逊多渠道发货 -->
    <MultiChannelShip ref="MultiChannelShipRef" @refresh="handleRefresh" v-if="dialogShow.MultiChannelShip" />
    <!-- 批量亚马逊多渠道发货 -->
    <MultiChannelShipBatch ref="MultiChannelShipBatchRef" @refresh="handleRefresh" v-if="dialogShow.MultiChannelShipBatch" />
    <!-- 批量上传二手机维修编号 -->
    <SkuRepairNumber ref="SkuRepairNumberRef" @refresh="handleRefresh" v-if="dialogShow.SkuRepairNumber" />
    <!-- 量修改订单地址 -->
    <EditRecipientAddress ref="EditRecipientAddressRef" @submit="handleConfirmSubmit" />
    <template v-if="resultsVisible">
      <el-dialog v-model="resultsVisible" title="批量取消eBay订单执行结果" width="500" :before-close="closeResults">
        <div v-loading="resultsLoading" style="min-height: 300px">
          <p v-for="i in resultsData" :key="i">订单：{{ i.order_sn }} 执行结果：{{ i.message }}</p>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="closeResults"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </div>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus"
import ConfirmInput from "@/components/ConfirmInput/index.vue"

const dialogShow = ref({
  DerivedCenter: false, // 导出中心
  MultiChannelShip: false, //亚马逊多渠道发货
  MultiChannelShipBatch: false, // 批量亚马逊多渠道发货
  SkuRepairNumber: false, // 批量上传二手机维修编号
})

import Accessory from "../../add/components/Accessory/index.vue"

import OrderConfirmInput from "../../Batch/OrderConfirmInput/index.vue"
import ReplaceSku from "../../Batch/ReplaceSku/index.vue"
import SplitOrder from "../../Batch/SplitOrder/index.vue"
import CombinedOrder from "../../Batch/CombinedOrder/index.vue"

// 亚马逊多渠道发货
import MultiChannelShip from "../../Batch/MultiChannelShip/index.vue"
const MultiChannelShipRef = ref()
// 批量亚马逊多渠道发货
import MultiChannelShipBatch from "../../Batch/MultiChannelShipBatch/index.vue"
const MultiChannelShipBatchRef = ref()
// 批量上传二手机维修编号
import SkuRepairNumber from "../../Batch/SkuRepairNumber/index.vue"
const SkuRepairNumberRef = ref()

// 批量修改发货仓库和运输方式
import ShippingMethod from "../../Batch/ShippingMethod_V2/index.vue"
// 批量手动标发订单
import MarkShipment from "../../Batch/MarkShipment/index.vue"
// 订单优先级
import OrderPriority from "../../Batch/OrderPriority/index.vue"

import OutNumber from "../../Batch/OutNumber/index.vue"

// 文本导入数据
import ImportNoNumber from "../../Batch/ImportNoNumber/index.vue"

import OrderExtractDtl from "../../Batch/OrderExtractDtl/index.vue"
const OrderExtractDtlRef = ref()
// 批量手动导入追踪号
import VImport from "./components/ImportTrackingNo/index.vue"
// 导出中心
import DerivedCenter from "@/components/DerivedCenter"

import EditRecipientAddress from "../../Batch/EditRecipientAddress/index.vue"

import { FUNCTION_OPERATE, confirm } from "./config"

import { isPermission } from "@/hooks/permission.js"
import api from "../../api"

// import req from '@/views/user/list/add/api/index'
import req from "@/views/user/list/add/api/index"
import { userAuthList } from "@/Auth/user.js"
const props = defineProps({
  rows: {
    type: Array,
    default: () => [],
  },
  totalInfo: {
    type: Object,
    default: () => ({}),
  },

  showOrderProfit: {
    // 是否显示订单利润
    type: Boolean,
    default: false,
  },
  // expandStatus: {
  //   type: Boolean,
  //   default: false,
  // },
  params: { type: Object, default: () => {} },
  // params: { type: Array, default: () => [] },
  type: { type: String, default: "" },
  active: { type: Number, default: 0 },
})
const originOption = ref({ reasonOption: [] })
import { getCountryOption } from "@/api/public.js"
onMounted(() => {
  nextTick(() => {
    // handleGetCountry()
  })
})
// // 获取站点
// const handleGetCountry = async () => {
//   try {
//     const { data } = await getCountryOption()
//     originOption.value.country = data.map((v) => ({
//       label: `${v.name} ${v.country}`,
//       value: v.country,
//       id: v.id,
//     }))
//   } catch (e) {
//     console.error(e)
//   }
// }

// 订单销售数据
import ShopSale from "./components/ShopSale/index.vue"
const shopSaleRef = ref()
const shopSaleShow = ref(false)
const openShopSaleList = () => {
  console.log(props.params)
  shopSaleShow.value = true
  nextTick(() => {
    shopSaleRef.value.open(props.params)
  })
  // emit("shopSaleList")
}

// 批量合并
const onMerge = async () => {
  // const rows = getSelectRows()
  if (!props?.rows?.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return
  }
  let countsList = []
  props?.rows?.forEach((item) => {
    let counts = {}
    item.child.forEach((val) => {
      counts[val.canMerged] ? counts[val.canMerged].push(val.id) : (counts[val.canMerged] = [val.id])
    })
    countsList.push(Object.values(counts))
  })
  countsList = countsList.flat(1)
  let merge = countsList.filter((v) => v.length != 1).map((v) => ({ order_ids: v }))

  let noMerge = countsList.filter((v) => v.length == 1).flat(1)
  await api.canMergedMerge(merge)
  await api.canMergedNoMerge({ ids: noMerge })
  ElMessage({ type: "success", message: "操作成功" })
  setTimeout(() => {
    emit("refresh")
  }, 900)
}
// 不合并订单
const onNoMerge = async () => {
  if (!props?.rows?.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return
  }
  // multipleSelection
  let countsList = []
  props?.rows?.forEach((item) => {
    countsList.push(...item.child.map((v) => v.id))
  })
  await api.canMergedNoMerge({ ids: countsList })
  ElMessage({ type: "success", message: "操作成功" })
  // getList()
  setTimeout(() => {
    emit("refresh")
  }, 900)
}

// 批量取消合并
const onCancelMerge = async () => {
  // console.log(props.rows)
  // const rows = getSelectRows()
  if (!props?.rows?.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return
  }
  api.mergedCancel({ orderIds: props?.rows?.map((v) => v.id) }).then((res) => {
    ElMessage({ type: "success", message: "操作成功" })

    setTimeout(() => {
      emit("refresh")
    }, 900)
  })
}

const expandStatus = ref(false)
const { type } = toRefs(props)
const router = useRouter()
const { proxy } = getCurrentInstance()

const downloadUrl = ref("")
const importUrl = ref("")

const currentConfirm = ref("shipmentInterception")

const getCurrentConfirm = computed(() => confirm[currentConfirm.value])

const emit = defineEmits(["refresh", "expand", "getParam", "setParamGet", "update:showOrderProfit", "shopSaleList"])
const showOrderProfitChange = (e) => {
  emit("update:showOrderProfit", e)
}
const batchVisible = reactive({
  replaceSku: false,
  splitOrder: false,
  combinedOrder: false,
  confirmInput: false,
  orderConfirmInput: false,

  editShipping: false,
  import: false,
  markShipment: false,
  cancel: false,
  orderPriority: false, //订单优先级
})
const affixRef = ref()

onActivated(() => {
  affixRef.value?.updateRoot()
})
const handleReq = async (data, msg = "操作成功!") => {
  try {
    await api.batchOperation(data)
    ElMessage.success(msg)
    setTimeout(() => {
      emit("refresh")
    }, 900)
  } catch (e) {
    console.warn("handleReq err", e)
  } finally {
  }
}

const handleConfirmSubmit = (e) => {
  const { input } = e
  const { rows = [] } = props
  const order_ids = rows.map((v) => v.id)
  let params = {}
  let msg
  switch (currentConfirm.value) {
    case "shipmentInterception":
      params = {
        order_remark: input,
        order_ids,
        handler: "order_intercept",
      }
      msg = "库内拦截成功！"
      break
    case "blacklist":
      params = {
        reason: input,
        order_ids,
        handler: "order_blacklist",
      }
      msg = "添加至黑名单成功！"
      break

    case "editShipping":
      params = {
        order_ids,
        handler: "order_modify_wms",
        ...input,
      }
      msg = "批量修改发货仓库和运输方式成功！"
      break
    case "markShipment": // 批量手动标发订单
      params = {
        handler: "order_hand_mark_shipment",
        ...input,
      }
      msg = "批量操作成功！"
      break
    case "operation":
      params = {
        handler: "order_modify_priority",
        priority: input,
        order_ids,
      }
      msg = "批量操作成功！"
      break
    // 批量修改收件地址
    case "recipientUpdate":
      params = {
        handler: "order_recipient_update",
        data: input,
      }
      msg = "批量操作成功！"
      console.log(params)
      break

    default:
      break
  }

  handleReq(params, msg)
  batchVisible.confirmInput = false
  batchVisible.markShipment = false

  batchVisible.orderPriority = false
  // batchVisible.orderConfirmInput = false
  currentConfirm.value = "shipmentInterception"
}

const handleConfirmInputSubmit = async (e) => {
  console.log(e)
  const { input } = e
  const { rows = [] } = props
  const order_ids = rows.map((v) => v.id)
  let params = {}
  let msg = ""
  switch (orderCurrentConfirm.value.type) {
    case "customer": // 批量修改客服人员
      params = { handler: "order_modify_customer", order_ids, ...input }
      msg = "批量操作成功！"
      break
    case "seller": // 批量修改销售人员
      params = { handler: "order_modify_seller", order_ids, ...input }
      msg = "批量操作成功！"
      break
    case "order_remark": // 订单备注
      params = { mode: 1, ids: order_ids, ...input }
      msg = "批量操作成功！"
      break
    case "shipping_remark": // 发货备注
      params = { mode: 3, ids: order_ids, ...input }
      msg = "批量操作成功！"
      break
    case "customer_service_remark": // 客服备注
      params = { mode: 4, ids: order_ids, ...input }
      msg = "批量操作成功！"
      break
    case "logistics_remark": // 物流备注
      params = { mode: 5, ids: order_ids, ...input }
      msg = "批量操作成功！"
      break

    /* ------- 订单操作 ------- */
    case "cancel": // 批量取消系统订单
      params = { ids: order_ids, ...input }
      msg = "批量取消系统订单成功！"
      break

    case "ebay_cancel": // 批量取消 ebay订单
      params = { order_ids, ...input, handler: "order_ebay_cancel" }
      // params = { order_ids, ...input }
      msg = "批量取消Ebay订单成功！"
      break
    case "return_trackingæ": // 批量生成回邮单号
      params = { order_ids, ...input, handler: "generate_return_tracking_num" }
      // 获取name
      params.return_warehouse_name = originOption.value.return_warehouse.find((v) => v.value == params.return_warehouse_id)?.label
      params.return_logistic_channel_name = originOption.value.return_logistic_channel.find((v) => v.value == params.return_logistic_channel_id)?.label
      msg = "保存成功"
      break

    case "apply_refund": // 批量申请全额退款
      params = { order_ids, ...input, handler: "apply_refund" }
      msg = "保存成功"
      break

    // 订单附件管理
    case "addAccessory": // 订单附件管理
      params = { ...input }
      msg = "保存成功"
      break
  }
  if (orderCurrentConfirm.value.type == "addAccessory") {
    console.log(params)

    if (params.attachment.find((v) => !v.type && v.name)) {
      return ElMessage({ showClose: true, message: "文件类型必填！", type: "warning" })
    }
    params.attachment = params.attachment.filter((v) => v.name)
  }
  let res = await handleReqApi(params, msg, orderCurrentConfirm?.value?.api)
  if (orderCurrentConfirm.value.type == "ebay_cancel") {
    resultsVisible.value = true
    openResults(res.data.batch_number, params.order_ids.length)
  }
  batchVisible.orderConfirmInput = false
}
const openResults = async (batch_number, length) => {
  resultsLoading.value = true
  if (resultsVisible.value) {
    setTimeout(async () => {
      try {
        let { data } = await api.batchResults({ batch_number })
        resultsData.value = data
        if (resultsData.value.length == length) {
          resultsLoading.value = false
        } else {
          openResults(batch_number, length)
        }
      } catch (error) {
        resultsLoading.value = false
      }
    }, 1000)
  }
}
const resultsLoading = ref(false)
const resultsVisible = ref(false)
const resultsData = ref([])
const closeResults = () => {
  resultsData.value = []
  setTimeout(() => {
    nextTick(() => {
      resultsLoading.value = false
      resultsVisible.value = false
    })
  }, 100)
}

const handleReqApi = async (data, msg = "操作成功!", apiUrl = () => {}) => {
  try {
    let res = await apiUrl(data)
    ElMessage.success(msg)
    setTimeout(() => {
      emit("refresh")
    }, 900)
    return res
  } catch (e) {
    console.warn("handleReq err", e)
  } finally {
  }
}
import { getWarehouseOptions, apiGetChannel } from "@/api/public"
// 弹窗 表单编辑 打开
const batchOptionsEvent = async (e, params = {}) => {
  console.log(e)
  let ids = props.rows.map((v) => v.id)
  let data = {}
  switch (e) {
    case "customer": // 批量修改客服人员
      data = { ...confirm.customer, length: ids.length, type: e }
      break
    case "seller": // 批量修改销售人员
      data = { ...confirm.seller, length: ids.length, type: e }
      break
    case "order_remark": // 订单备注
      data = { ...confirm.order_remark, length: ids.length, type: e }
      data.title = "订单备注"
      data.fieldOptions[1].label = "订单备注"
      data.fieldOptions[1].placeholder = "订单备注"
      break
    case "shipping_remark": // 发货备注
      data = { ...confirm.order_remark, length: ids.length, type: e }
      data.title = "发货备注"
      data.fieldOptions[1].label = "发货备注"
      data.fieldOptions[1].placeholder = "发货备注"
      break
    case "customer_service_remark": // 客服备注
      data = { ...confirm.order_remark, length: ids.length, type: e }
      data.title = "客服备注"
      data.fieldOptions[1].label = "客服备注"
      data.fieldOptions[1].placeholder = "客服备注"
      break
    case "logistics_remark": // 物流备注
      data = { ...confirm.order_remark, length: ids.length, type: e }
      data.title = "物流备注"
      data.fieldOptions[1].label = "物流备注"
      data.fieldOptions[1].placeholder = "物流备注"
      break

    case "cancel": // 批量取消系统订单
      data = { ...confirm.cancel, length: ids.length, type: e }
      break

    case "ebay_cancel": // 批量取消Ebay订单
      data = { ...confirm.ebay_cancel, length: ids.length, type: e }
      break

    // 许操作
    case "return_trackingæ": // 批量生成回邮单号
      const returnWarehouse = (await getWarehouseOptions({ status: 1, is_back: 1 }))?.data
      originOption.value.return_warehouse = returnWarehouse
      data = { ...handleConfirm.return_trackingæ, length: ids.length, type: e, originOption: originOption.value }
      break

    case "apply_refund": // 批量申请全额退款
      await getFirstOption()
      getRefundReason()
      data = {
        ...handleConfirm.apply_refund,
        // length: ids.length,
        type: e,
        originOption: {
          ...originOption.value,
          firstOption: originOption.value.firstOption.filter((v) => v.platform_id == props.rows?.[0].platform_id),
        },
      }
      break

    // 订单附件管理
    case "addAccessory": // 订单附件管理
      data = {
        ...handleConfirm.addAccessory,
        type: e,
        form: {
          id: props.rows?.[0]?.id,
          order_sn: props.rows?.[0]?.order_sn,
          attachment: props.rows?.[0]?.attachment?.length ? props.rows?.[0]?.attachment : [{}],
        },
      }
      console.log(data)
      break
  }
  // 批量取消Ebay订单
  if (e == "ebay_cancel" && props.rows.find((v) => v.platform_id != 1)) {
    return ElMessage.warning("该功能仅支持取消ebay平台订单，请勿选择其他平台的订单")
  }
  // 批量生成回邮单号
  if (e == "return_trackingæ" && props.rows.find((v) => ![5, 6, 7, 8].includes(v.order_status))) {
    return ElMessage.warning("可执行操作的订单:已发货、派送在途、已签收、拒收")
  }

  orderCurrentConfirm.value = data
  batchVisible.orderConfirmInput = true
}
// 需要操作 表单配置
const handleConfirm = {
  addAccessory: {
    title: "订单附件管理",
    width: 760,
    api: api.attachment,
    form: {},
    fieldOptions: [{ slot: "addAccessory" }],
  },
  // 批量获取回邮单号
  return_trackingæ: {
    title: "批量获取回邮单号",
    api: api.batchOperation,
    length: 0,
    form: {},
    fieldOptions: [
      {
        field: "return_warehouse_id",
        label: "回邮仓库",
        type: "select",
        style: { width: "100%" },
        originField: "return_warehouse",
        change: (e) => {
          apiGetChannel({ warehouse: [e], source_os: "oms" }).then((res) => {
            originOption.value.return_logistic_channel = res.data.map((v) => ({ label: v.channel_name, value: v.id }))
          })
        },
      },
      {
        field: "return_logistic_channel_id",
        label: "回邮物流渠道",
        type: "select",
        style: { width: "100%" },
        originField: "return_logistic_channel",
      },
    ],
    rules: {
      return_warehouse_id: [{ required: true, message: "请选择", trigger: "change" }],
      return_logistic_channel_id: [{ required: true, message: "请选择", trigger: "change" }],
    },
    tips: "已发货的订单，获取退货的回邮单号，目前只支持欧洲国家使用回邮服务！",
  },

  // 批量申请全额退款
  apply_refund: {
    title: "批量申请全额退款",
    width: "700",
    api: api.batchOperation,
    formOptions: { inline: true, labelPosition: "top" },
    form: {},
    fieldOptions: [
      {
        field: "primary_cause_id",
        label: "一级退款原因",
        type: "select",
        originField: "firstOption",
        style: { width: "200px" },
        change: async (e, formData) => {
          formData.secondary_cause_id = ""
          originOption.value.reasonOption = []
          await getReasonOption(e)
          orderCurrentConfirm.value.originOption.reasonOption = originOption.value.reasonOption
        },
      },
      { field: "secondary_cause_id", label: "二级退款原因", type: "select", originField: "reasonOption", style: { width: "200px" } },
      { type: "br" },
      {
        field: "is_dispute",
        label: "存在纠纷",
        type: "select",
        options: {
          data: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        style: { width: "200px" },
      },
      {
        field: "dispute_type",
        label: "纠纷类型",
        type: "select",
        origin: "refund_dispute_type",
        style: { width: "200px" },
        show: ({ model }) => model.is_dispute === 1,
      },
      {
        field: "is_cut_payment",
        label: "是否扣款",
        type: "select",
        style: { width: "200px" },
        options: {
          data: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        show: ({ model }) => model.dispute_type === 3,
      },
      { type: "br" },

      {
        field: "cargo_handler",
        label: "货物处理",
        type: "select",
        origin: "cargo_handler",
        style: { width: "200px" },
        // change: cargoHandlerChange,
      },
      {
        field: "is_generate_return",
        label: "自动生成退件单",
        type: "select",
        options: {
          data: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        style: { width: "200px" },
        show: ({ model }) => [2, 3].includes(+model?.cargo_handler),
      },

      { type: "br" },
      {
        field: "is_api_refund",
        label: "是否api退款",
        type: "select",
        options: {
          data: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        style: { width: "200px" },
      },
      {
        field: "platform_refund_reason",
        label: "平台退款原因",
        type: "select",
        originField: "refundReason",
        style: { width: "200px" },
        show: ({ model }) => model?.is_api_refund == 1,
      },
      { type: "br" },
      {
        field: "is_cancel_order",
        label: "是否取消原单（未发货订单）",
        type: "select",
        options: {
          data: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        style: { width: "200px" },
      },

      {
        field: "customer_refund_description",
        type: "textarea",
        label: "客户退款描述",
        style: { width: "600px" },
        autosize: { minRows: 2, maxRows: 6 },
        full: true,
      },
    ],
    rules: {
      primary_cause_id: [{ required: true, message: "请选择一级退款原因", trigger: "change" }],
      secondary_cause_id: [{ required: true, message: "请选择二级退款原因", trigger: "change" }],
      is_dispute: [{ required: true, message: "请选择存在纠纷", trigger: "change" }],
      dispute_type: [{ required: true, message: "请选择纠纷类型", trigger: "change" }],
      is_cut_payment: [{ required: true, message: "请选择是否扣款", trigger: "change" }],
      cargo_handler: [{ required: true, message: "请选择货物处理", trigger: "change" }],

      is_api_refund: [{ required: true, message: "请选择是否api退款", trigger: "change" }],
      platform_refund_reason: [{ required: true, message: "请选择平台退款原因", trigger: "change" }],
      is_cancel_order: [{ required: true, message: "请选择是否取消原单", trigger: "change" }],
      customer_refund_description: [{ required: true, message: "请输入客户退款描述", trigger: "blur" }],
    },
  },
}
// 一级退款原因
import { getReasonList } from "@/views/user/refund//api/index"
const getFirstOption = async () => {
  let firstOption = (await getReasonList({ platform_id: "" })).data
    .filter((v) => v.parent_id == 0 && v.is_enable == 1)
    .map((v) => ({
      ...v,
      label: v.reason,
      value: v.id,
    }))
  originOption.value.firstOption = firstOption
}
// 平台退款原因
import { overallOptions } from "@/api/public"

const getRefundReason = async () => {
  // eBay_refund_reason
  // props.rows
  let platform = {
    1: "eBay_refund_reason",
    2: "amazon_adjustment_reason",
  }
  originOption.value.refundReason = (await overallOptions({ params: [platform[props.rows?.[0]?.platform_id]], option: "new" })).data?.[platform[props.rows?.[0]?.platform_id]]
}
// 二级退款原因
import { getReasonOptions } from "@/views/user/refund/api/index"
const getReasonOption = async (id) => {
  try {
    const { data } = await getReasonOptions({ parent_id: id })
    originOption.value.reasonOption = data?.filter((v) => v.is_enable == 1)?.map((n) => ({ label: n.reason, value: n.id }))
  } catch (e) {}
}
// 切换 货物处理   重置 退件仓库 & 自动生成退件单 & 退件追踪号
const cargoHandlerChange = async (e) => {
  // props.info.return_warehouse_id = ""
  // props.info.is_generate_return = 1
  // props.info.tracking_number = ""
  // 退货上架
  // if (e == 2) {
  //   const res = await getWarehouseOptions({ status: 1 })
  //   warehouseOpt.value = res.data
  //   props.info.return_warehouse_id = props.info.ship_warehouse_id || ""
  //   props.info.tracking_number = props.info.real_track_no
  //   rules.return_warehouse_id[0].required = false
  //   rules.tracking_number[0].required = false
  // }
  // if (e == 3) {
  //   const res = await getWarehouseOptions({ status: 1, is_back_warehouse: 1 })
  //   warehouseOpt.value = res.data
  //   rules.return_warehouse_id[0].required = true
  //   rules.tracking_number[0].required = true
  //   // otto 默认 退件追踪号
  //   if (props.info.platform_id == 3) {
  //     props.info.tracking_number = props.info?.return_number
  //     props.info.return_warehouse_id = res.data?.find((v) => v.label == "MIC德国仓")?.value
  //   }
  // }
  // warehouseOpt.value = []
}

// 批量上传海外仓出库单号
const OutNumberRef = ref()
const handleOnOutNumber = () => {
  OutNumberRef?.value?.open()
}

// 同步订单到FBA发货（亚马逊）
const handleSyncFBA = () => {}

const handleBatchOperate = (n) => {
  const fn = {
    /* ------- 运输方式与追踪号 ------- */
    // orderExtract: handleOrderExtract, // 批量提取订单信息

    onMultiChannelShip: handleMultiChannelShip, // 单个 亚马逊多渠道发货
    onMultiChannelShipBatch: handleMultiChannelShipBatch, // 批量 亚马逊多渠道发货

    onOutNumber: handleOnOutNumber, // 批量上传海外仓出库单号
    orderStrategy: handleOrderStrategy, // 批量执行订单策略
    editShippingMethod: handleShippingMethod, // 批量修改发货仓库和运输方式
    generateTrackingNo: handleGenerateTrackingNo, // 批量手动预生成追踪号
    manuallyImportTrackingNo: handleManuallyImportTrackingNo, // 批量手动导入追踪号
    manuallyImportTrackingNo1: handleManuallyImportTrackingNo1, // 批量手动上传追踪号
    onSkuRepairNumber: handleSkuRepairNumber, // 批量上传二手机维修编号
    onReturnTracking: handleReturnTracking, // 批量生成回邮单号
    /* ------- 发货与标发 ------- */
    orderShipped: handleOrderShipped, // 批量设置订单已发货
    orderForShipment: handleOrderForShipment, // 批量手动标发订单
    notToPublish: handleNotToPublish, // 批量设置不标发
    reUploadTrackingNo: handleReUploadTrackingNo, // 批量重新上传追踪号到平台
    syncOverseasWarehouse: handleSyncOverseasWarehouse, // 批量手动同步海外仓发货
    syncFBA: handleSyncFBA, // 同步订单到FBA发货（亚马逊） 暂未使用

    /* ------- 人员与备注信息 ------- */
    editCustomer: editCustomer, // 批量修改客服人员
    editSeller: editSeller, // 批量修改销售人员
    editRemark1: handleEditRemarOreder, // 订单备注
    editRemark3: handleEditRemarkShipping, // 发货备注
    editRemark4: handleEditRemarkCustomer, // 客服备注
    editRemark5: handleEditRemarkCustomer11111, // 物流备注
  }
  const noMatchRow = ["manuallyImportTrackingNo", "onOutNumber", "manuallyImportTrackingNo1"]
  const rows = getSelectRows()
  if (!rows?.length && !noMatchRow.includes(n.fn)) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return
  }
  if (fn[n.fn]) {
    fn[n.fn]?.()
  }
}

const getSelectRows = () => {
  const { rows = [] } = props
  if (!rows?.length) {
    return []
  }
  return rows
}

// 批量操作 弹窗关闭 回调
const handleBeforeClose = async (action, instance, done, handler = "") => {
  const ids = getSelectRows().map((n) => n.id)
  if (action === "confirm") {
    try {
      instance.confirmButtonLoading = true
      instance.confirmButtonText = "处理中.."
      await handleReq({
        order_ids: ids,
        handler,
      })
    } catch (e) {
      console.error(e)
    } finally {
      instance.confirmButtonLoading = false
      done()
    }
  } else {
    done()
  }
}

/* ------- 运输方式与追踪号 ------- */
//  单个 亚马逊多渠道发货
const handleMultiChannelShip = () => {
  const rows = getSelectRows()
  if (rows.length != 1) {
    return ElMessage({ showClose: true, message: "请选择一条数据！", type: "warning" })
  }
  if (rows[0].shipping_type == 1) {
    return ElMessage.warning("FBA订单不支持多渠道发货！")
  }
  if (rows[0].order_status != 1) {
    return ElMessage.warning("非已确认状态订单，不允许做多渠道发货！")
  }
  dialogShow.value.MultiChannelShip = true
  nextTick(() => {
    MultiChannelShipRef.value.open(rows[0])
  })
}
//  批量 亚马逊多渠道发货
const handleMultiChannelShipBatch = () => {
  const rows = getSelectRows()
  if (rows.find((v) => v.shipping_type == 1)) {
    return ElMessage.warning("FBA订单不支持多渠道发货！")
  }
  if (rows.find((v) => v.order_status != 1)) {
    return ElMessage.warning("非已确认状态订单，不允许做多渠道发货！")
  }
  // 只允许单个店铺
  if ([...new Set(rows.map((v) => v.shop_id))].length != 1) {
    return ElMessage.warning("批量操作多渠道发货只允许单个店铺的订单操作，请检查！")
  }

  dialogShow.value.MultiChannelShipBatch = true
  nextTick(() => {
    MultiChannelShipBatchRef.value.open(rows, "batch")
  })
}

// orderExtract: handleOrderExtract, // 批量提取订单信息
// 批量提取订单信息
const handleOrderExtract = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  OrderExtractDtlRef?.value.open(rows)
}

// 批量执行订单策略
const handleOrderStrategy = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量执行订单策略",
    content: (
      <p>
        确认执行<span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条订单订单策略？
      </p>
    ),
    tips: "选中的订单将会重新执行订单排程策略，发货仓库和运输方式可能会发生变更！",
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_exec_strategy")
    },
  })
}
// 批量修改发货仓库和运输方式
const handleShippingMethod = () => {
  currentConfirm.value = "editShipping"
  batchVisible.editShipping = true
}
// 批量手动预生成追踪号
const handleGenerateTrackingNo = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量手动预生成追踪号",
    content: (
      <p>
        确认手动与生成选中的
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条数据追踪号？
      </p>
    ),
    tips: "连续3次获取追踪号失败时，订单会进入问题单，问题原因：预生成追踪号失败",
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_gen_tracking_number")
    },
  })
}
// 批量手动上传追踪号
const ImportNoNumberRef = ref()
const handleManuallyImportTrackingNo1 = () => {
  ImportNoNumberRef?.value?.open({
    title: "批量手动上传追踪单号",
    header: `批量手动上传追踪号(从Excel中复制 或 以“Tab”制表符号分隔，一行一条记录)，限制为200条，<span class='text-red'>*</span>为必填项`,
    columns: [
      { label: "系统订单号", value: "customer_order_no", width: "240", required: true },
      { label: "物流商单号", value: "api_number", width: "240", required: true },
      { label: "真实追踪号", value: "tracking_number", width: "240", required: true },
      { label: "物流商转单号", value: "transfer_number", width: "130" },
      { label: "尾程商转单号", value: "frt_tracking_number", width: "130" },
      { label: "面单号", value: "label_barcode", width: "130" },
    ],
    getHistory: api.uploadTraceNumberHistory,
    save: api.uploadTraceNumber,
  })
}
// 批量手动导入追踪号
const VImportRef = ref()
const handleManuallyImportTrackingNo = async () => {
  const res = await api.getImportTpl({ tpl_name: "批量手动导入追踪号模板.xlsx" })
  downloadUrl.value = res.data.url
  importUrl.value = "/order/batch/operation"
  batchVisible.import = true
  VImportRef.value.initUpload()
}
const importParamsFormatter = (query) => {
  return {
    oss_url: query,
    handler: "order_import_tracking_number",
  }
}
const importCallBack = ({ downloadUrl, fileName, ossUrl }) => {
  handleReq(
    {
      oss_url: `import${ossUrl.split("import")[1]}`,
      handler: "order_import_tracking_number",
    },
    "导入成功！"
  ).then(() => {
    batchVisible.import = false
  })
}

// 批量上传二手机维修编号
const handleSkuRepairNumber = () => {
  const rows = getSelectRows()
  if (props.rows.find((v) => ![1, 2].includes(v.order_status) || v.shipping_type == 1)) {
    return ElMessage.warning("可执行操作的订单:已确认、问题订单、FBM (卖家发货) 订单")
  }
  dialogShow.value.SkuRepairNumber = true
  nextTick(() => {
    SkuRepairNumberRef.value.open(rows)
  })
}

// 批量生成回邮单号
const handleReturnTracking = () => {
  // 批量生成回邮单号
  console.log("批量生成回邮单号")
  //
  batchOptionsEvent("return_trackingæ")
}

/* ------- 发货与标发 ------- */

// 批量设置订单已发货
const handleOrderShipped = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量设置订单已发货",
    content: (
      <p>
        确认设置
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条数据订单已发货？
      </p>
    ),
    tips: "订单线下已发货或其他常见，系统上直接更新订单状态为“已发货”",
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_set_shipped")
    },
  })
}
// 批量手动标发订单
const handleOrderForShipment = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  currentConfirm.value = "markShipment"
  batchVisible.markShipment = true
}
// 批量设置不标发
const handleNotToPublish = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量设置不标发",
    content: (
      <p>
        确认设置
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条数据订单不标记发货？
      </p>
    ),
    tips: "操作后，系统将使用订单最新的追踪号重新标发，部分平台会更新后台的发货时间",
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_no_mark_shipment")
    },
  })
}
// 批量重新上传追踪号到平台
const handleReUploadTrackingNo = (e) => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量重新上传追踪号到平台",
    content: (
      <p>
        确认重新上传
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条数据追踪号到平台？
      </p>
    ),
    tips: "操作后，系统将使用订单最新的追踪号重新标发，部分平台会更新后台的发货时间",
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_re_mark_shipment")
    },
  })
}
// 批量手动同步海外仓发货
const handleSyncOverseasWarehouse = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量手动同步海外仓发货",
    content: (
      <p>
        确认同步 <span class="text-[#3366F1] px-[4px]">{ids.length}</span> 条数据到海外仓发货？{" "}
      </p>
    ),
    tips: (
      <div>
        说明：发货仓库必须是<span class="text-[#FF0000]">海外仓</span> ，且订单状态为<span class="text-[#FF0000]">已确认时</span>，才能同步到海外仓！
      </div>
    ),
    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_sync_overseas_wms")
    },
  })
}
// 批量标记物流退回
const handleBatchRemark = () => {
  const rows = getSelectRows()
  if (!rows.length) {
    return ElMessage({ showClose: true, message: "请选择1个订单！", type: "warning" })
  }
  if (rows.find((v) => v.order_status != 5)) {
    return ElMessage.warning("只能针对已发货订单进行操作")
  }
  proxy?.confirm({
    title: `确认操作`,
    content: <p>确定对{rows.length}个订单批量增加问题原因：已发货物流退回</p>,

    beforeClose: async (action, instance, done) => {
      await handleBeforeClose(action, instance, done, "order_shipped_return_mark")
    },
  })
}
// 批量申请全额退款
const handleApplyRefund = () => {
  const rows = getSelectRows()
  if (!rows.length) {
    return ElMessage({ showClose: true, message: "请选择1个订单！", type: "warning" })
  }
  if ([...new Set(rows.map((v) => v.platform_id))].length != 1) {
    return ElMessage({ showClose: true, message: "所选订单包含多个平台订单，批量申请全额退款只支持处理同一平台订单。", type: "warning" })
  }

  if (rows.find((v) => [1, 2].includes(v.refund_status))) {
    return ElMessage({ showClose: true, message: "存在已部分退款或全部退款的订单，不可以批量申请全额退款。", type: "warning" })
  }
  if (rows.find((v) => v.original_order_amount == 0)) {
    return ElMessage({ showClose: true, message: "批量申请全额退款，支付金额为0，不生成退款单", type: "warning" })
  }
  batchOptionsEvent("apply_refund")
}
const EditRecipientAddressRef = ref()
const handleRecipientUpdate = () => {
  const rows = getSelectRows()
  if (!rows.length) {
    return ElMessage({ showClose: true, message: "至少选择1个订单！", type: "warning" })
  }

  if (rows.find((v) => ![1, 2].includes(v.order_status))) {
    return ElMessage({ showClose: true, message: "只允许“已确认，问题订单”状态的订单进行操作!", type: "warning" })
  }
  currentConfirm.value = "recipientUpdate"
  EditRecipientAddressRef.value.open(rows)
}

/* ------- 人员与备注信息 ------- */
// 批量修改客服人员
const editCustomer = () => {
  batchOptionsEvent("customer")
}
// 批量修改销售人员
const editSeller = () => {
  batchOptionsEvent("seller")
}
const orderCurrentConfirm = ref({})
// 订单备注
const handleEditRemarOreder = (key) => {
  batchOptionsEvent("order_remark")
}
// 发货备注
const handleEditRemarkShipping = () => {
  batchOptionsEvent("shipping_remark")
}
// 客服备注
const handleEditRemarkCustomer = () => {
  batchOptionsEvent("customer_service_remark")
}
// 物流备注
const handleEditRemarkCustomer11111 = () => {
  batchOptionsEvent("logistics_remark")
}

const handleRefresh = (param = {}) => {
  if (Object.keys(param).length) {
    emit("setParamGet", param)
  } else {
    setTimeout(() => {
      emit("refresh")
    }, 900)
  }
}

const commonBaseBatchFnMatchRule = {
  order_re_inspection: {
    title: "批量重检订单",
    content: "确定要重检订单?",
    confirmFn: async (order_ids) => {
      await handleReq({ order_ids, handler: "order_re_inspection" })
    },
  },
  order_set_confirmed: {
    title: "批量确认通过",
    content: "确认通过?",
    confirmFn: async (order_ids) => {
      await handleReq({ order_ids, handler: "order_set_confirmed" })
    },
  },
}
const commonBaseBatchFn = (type) => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids || !ids.length) {
    return ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    })
  }
  const matched = commonBaseBatchFnMatchRule[type]
  if (!matched || !ids?.length) return
  const { confirmFn } = matched
  proxy?.confirm({
    title: matched.title || "批量操作",
    content: matched.content || "",
    tips: matched.tips || "",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          if (confirmFn && typeof confirmFn === "function") await confirmFn(ids)
          instance.confirmButtonLoading = true
          instance.confirmButtonText = "处理中.."
        } catch (e) {
          console.error(e)
        } finally {
          instance.confirmButtonLoading = false
          done()
          setTimeout(() => {
            emit("refresh")
          }, 900)
        }
      } else {
        done()
      }
    },
  })
}
/* ------- 订单操作 ------- */
// 订单附件管理
const handleAddAccessory = () => {
  const rows = getSelectRows()
  if (rows.length != 1) {
    return ElMessage.warning("请选择1个订单！")
  }
  batchOptionsEvent("addAccessory")
}

// 新增订单
const handleAdd = () => {
  router.push(`/user/list/create?id=add&type=add`)
}
// 批量取消系统订单
const handleCancel = () => {
  batchOptionsEvent("cancel")
}
// 批量重新计算订单利润
const batchQuoteRate = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  req.againCalculate({ orderIds: rows.map((v) => v.id) })
  ElMessage.success("操作成功！")
}
// 拆分订单
const handleSplitOrder = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  if (rows.length > 1) {
    ElMessage.warning("只能拆分单个订单")
    return
  }
  const products = rows[0]?.items
  if (!products.length) {
    ElMessage.warning("订单无法拆分")
    return
  }
  // FBA订单不允许拆分/合并
  if (rows[0].shipping_type == 1 && rows[0].platform_id != 1) {
    ElMessage.warning("FBA订单不允许拆分/合并")
    return
  }
  // if (products.length === 1 && +products?.[0]?.quantity === 1 ) {
  //   ElMessage.warning("订单无法拆分")
  //   return
  // }
  // build_order_type 订单创建类型
  if (rows[0]?.build_order_type == 1) {
    ElMessage.warning("手动新增订单无法拆分，请复制创建子订单！")
    return
  }
  if (products.length === 1 && products?.[0]?.quantity === 1 && products?.[0]?.is_assemble != 1) {
    ElMessage.warning("订单无法拆分")
    return
  }
  if (rows[0]?.is_split_order == 1 || rows[0]?.is_consolidate_order == 1 || rows[0]?.is_original_order == 1) {
    ElMessage.warning("已拆分/合并的订单，不允许再次拆分/合并")
    return
  }
  if (![1, 2].includes(rows[0]?.order_status)) {
    ElMessage.warning("非已确认、问题订单状态的订单不可拆分！")
    return
  }

  batchVisible.splitOrder = true
}
// 合并订单
const handleCombinedOrder = () => {
  const rows = getSelectRows()
  if (rows.length < 2) {
    return ElMessage.warning("请至少选择2个订单！")
  }

  // FBA订单不允许拆分/合并
  if (rows.find((v) => v.shipping_type == 1)) {
    return ElMessage.warning("FBA订单不允许拆分/合并")
  }

  if (rows.find((v) => v.is_split_order == 1 || v.is_consolidate_order == 1)) {
    return ElMessage.warning("已拆分/合并的订单，不允许再次拆分/合并")
  }
  if ([...new Set(rows.map((v) => v.platform_id))].length > 1) {
    return ElMessage.warning("订单需同时满足同平台同店铺才可合并！")
  }
  batchVisible.combinedOrder = true
}
// 库内拦截（未发货）
const handleLibraryIntercept = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择订单！")
  }
  if (rows.find((v) => ![1, 2, 3, 4].includes(v.order_status))) {
    return ElMessage.warning("订单状态不为‘已确认’、‘问题单’、‘采购缺货’、‘待发货’，不允许库内拦截。")
  }

  currentConfirm.value = "shipmentInterception"
  batchVisible.confirmInput = true
}
// 添加至黑名单
const handleBlacklist = () => {
  const ids = getSelectRows().map((n) => n.order_sn)
  if (ids.length != 1) {
    return ElMessage.warning("请选择1个订单！")
  }
  currentConfirm.value = "blacklist"
  batchVisible.confirmInput = true
}
// 导出发票
const handleInvoice = () => {
  const ids = getSelectRows().map((n) => n.order_sn)
  if (ids.length != 1) {
    return ElMessage.warning("请选择1个订单！")
  }
  api.orderInvoice({ order_sn: ids[0] }).then((res) => {
    window.open(res.data.invoice_link)
  })
}
// 批量初始化订单
const handleInit = () => {
  const ids = getSelectRows().map((n) => n.id)
  if (!ids?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  proxy?.confirm({
    title: "批量初始化订单",
    content: (
      <p>
        确认初始化选中的
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条订单数据？
      </p>
    ),
    tips: "订单初始化后，订单的数据和状态都将恢复到刚进入系统时的情况，并重新执行系统检测流程",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = "处理中.."
          await api.batchInit({ ids })
        } catch (e) {
          console.error(e)
        } finally {
          instance.confirmButtonLoading = false
          done()
          setTimeout(() => {
            emit("refresh")
          }, 900)
        }
      } else {
        done()
      }
    },
  })
}
// 批量替换订单SKU
const handleChangeSku = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  batchVisible.replaceSku = true
}
// 批量取消ebay订单
const handleCancelEbay = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  batchOptionsEvent("ebay_cancel")
}
// 批量修改订单优先级别
const handleOperation = () => {
  const rows = getSelectRows()
  if (!rows?.length) {
    return ElMessage.warning("请选择1个订单！")
  }
  currentConfirm.value = "operation"
  batchVisible.orderPriority = true
}

// 快速查询  标发失败订单
const queryShipmentStatus = () => {
  emit("setParamGet", { mark_shipment_status: [4] })
}
// 全部展开 / 收起
const handleExpand = () => {
  expandStatus.value = !expandStatus.value
  emit("expand", expandStatus.value)
}
// 导出中心
const DerivedCenterRef = ref()
const expt = async () => {
  const records = getSelectRows().map((i) => i.order_sn)
  const uniqueArray = [...new Set(records)]
  let condition = {}
  if (uniqueArray.length) {
    condition = {
      query: [{ field: "order_sn", queryType: "terms", value: uniqueArray }],
    }
  } else {
    condition = { query: props.params }
  }

  // <!-- 导出中心 -->
  // <DerivedCenter ref="DerivedCenterRef" v-if="dialogShow.DerivedCenter">

  // DerivedCenterRef.value.open({
  //   tag_name: "order_sku_flatten",
  //   tag_names: "order_sku",
  //   condition,
  //   importBtnSlot: "importBtn",
  // })

  dialogShow.value.DerivedCenter = true
  nextTick(() => {
    DerivedCenterRef.value.open({
      tag_name: "order_sku_flatten",
      tag_names: "order_sku",
      condition,
      importBtnSlot: "importBtn",
    })
  })
}
const outerExport = async (module, moduleName) => {
  await DerivedCenterRef.value.outerExport(module, moduleName)
  ElMessage.success("正在导出")
}
defineExpose({
  batchOptionsEvent,
})
</script>

<style lang="scss" scoped>
// .link {
//   width: calc(100% - 16px);
//   height: 1px;
//   background: #e6e7e9;
//   margin: 16px 8px 8px 8px;
// }
// .action_bar {
//   border-bottom: 1px solid #e6e7e9;
//   margin: 0 8px;

//   .total {
//     font-size: 14px;
//     font-weight: 400;
//     color: #666;
//     line-height: 17px;
//     white-space: nowrap;
//     display: flex;
//     align-items: center;

//     &::before {
//       content: "";
//       width: 6px;
//       height: 6px;
//       background: #3487ff;
//       margin-right: 5px;
//       border-radius: 5px;
//     }

//     span {
//       color: #333;
//     }
//   }
// }

.dropdownTitle {
  font-size: 12px;
  padding: 8px 16px 0 0;
  color: #9da1ad;
  margin-left: 8px;

  &:not(:first-child) {
    border-top: 1px solid var(--base-border-color);
  }
}
.template {
  :deep(.el-dialog__footer) {
    .el-button {
      margin-left: 12px !important;
    }
  }
}
</style>
